import _ from "lodash";
import Vue from "vue";
// import service from "@service";
const service = () => {

}
import { getStaffAsync } from "./components";
import {
    getSrDynamicElementAsync,
    getIVRAsync, checkStaffAsync,
    examinationPlanAsync,
    examinationTemplateAsync
} from "./components";


import { flatNodesToNodes, treeFilter, getStringSet } from "@utils";
import {selectDeptList, selectRoleList, selectUserList, selectPatientList,selectOrderItemDictList, selectDiagnosisDictList} from "@/service/api.js"
const noop = function () { };

const getEmptyElementMatchItem = () => {
    return {
        element: null,
        matchMethod: null,
        matchValue: null,
        key: `${Date.now()}_${Math.floor(Math.random() * 1000)}`,
    };
};

export const getElementMatchItemsRender = () => {
    return (h, vm, item, data, handle) => {
        let itemList = [];

        data = data || []; // getEmptyElementMatchItem()

        const itemInputHandle = (value, index) => {
            data[index] = value;
            handle([...data]);
        };

        const addHandle = () => {
            handle(data.concat([getEmptyElementMatchItem()]));
        };

        const deleteHandle = (index) => {
            handle(data.filter((v, i) => i !== index));
        };

        let canDeleteSign = true; // data.length > 1;

        data.forEach((item, index) => {
            itemList.push(
                <ElementMatchItemComponent
                    class="afterTop-4"
                    key={item.key}
                    indexKey={item.key}
                    value={item}
                    canDeleteSign={canDeleteSign}
                    on-input={(value) => itemInputHandle(value, index)}
                    on-delete={() => deleteHandle(index)}
                />
            );
        });

        return (
            <div>
                {itemList}
                <div class="mt-4">
                    <el-button type="primary" on-click={addHandle}>
                        新增
                    </el-button>
                </div>
            </div>
        );
    };
};

/**
 *
 * @param {Object} staffSelectConfig 员工选择组件的配置
 */

export const getStaffFormItemRender = ({
    disabled,
    staffSelectConfig,
} = {}) => {

    return getPaginationSelectRenderGenerater(
        {
            asyncHandle: getStaffAsync(staffSelectConfig),
            configName: "staffSelectConfig",
            showHandle: (data) => {

                if (Array.isArray(data)) {
                    return data.length
                        ? data.map((v) => `${v.staffName}${v?.staffId ? `(${v?.staffId})` : ''}`).join(",")
                        : "";
                } else {

                    return data ? `${data.staffName}(${data.staffId})` : "";
                }

            },
        },
        { disabled, staffSelectConfig }
    );

};

export const getSrDynamicElementFormItemRender = ({
    disabled,
    componentProps,
} = {}) => {
    return getPaginationSelectRenderGenerater(
        {
            asyncHandle: getSrDynamicElementAsync,
            showHandle: (data) => {
                if (Array.isArray(data)) {
                    return data.length
                        ? data.map((v) => v.fctNm).join(",")
                        : "";
                } else {
                    return data ? `${data.fctNm}(${data.fctNo})` : "";
                }
            },
        },
        { disabled, componentProps }
    );
};

export const getPaginationSelectRenderGenerater = (
    { asyncHandle, configName = "componentProps", showHandle },
    { disabled, ...otherConfigs } = {}
) => {
    let isMultiple = _.get(otherConfigs, `${configName}.isMultiple`);

    return (h, vm, item, data, handle) => {
        const selectHandle = async (e) => {
            if (disabled) {
                return e.stopPropagation();
            }

            let tempList = await asyncHandle(vm, {
                data,
                // [configName]
                componentProps: otherConfigs[configName],
            });

            if (tempList && (!isMultiple || tempList.length)) {
                if (isMultiple) {
                    handle(tempList);
                } else {
                    handle(_.get(tempList, "[0]"));
                }
            }
        };
        const clearHandle = (e) => {
            handle(null);
            e.stopPropagation();
        };

        let showText = showHandle(data);

        return (
            <div
                class={`input-click-select inform relative w-100 ${disabled ? "disabled" : ""
                    }`}
                on-click={selectHandle}
            >
                {data ? (
                    <span>{showText}</span>
                ) : (
                    <span class="color999 text-12">点击选择</span>
                )}
                {data && !disabled ? (
                    <i
                        class="el-icon-circle-close closIcon"
                        style="margin-top: -4px"
                        on-click={clearHandle}
                    />
                ) : null}
            </div>
        );
    };
};

export function getCascaderFormRender(
    cascaderConfigs = {},
    serviceConfigs = {}
) {
    let {
        clearable = true,
        disabled = false,
        placeholder = "请选择",
        showAllLevels = true,
        props,
        options = [],
        filterable = false,
        componentsType,
        filterMethod,
        collapseTags = true,
    } = cascaderConfigs;
    let {
        service: serviceName,
        idName = "id",
        queryIdName = "id",
        paramsHandle,
        treeMapChangeHandle,
        treeMapKey,
        comParams = {},
        initParentCode = "0",
        initInputKey,
        dataType = "data"
    } = serviceConfigs;

    let treeMap = {};
    let treeData = [...options];

    if (!treeMapChangeHandle) {
        treeMapChangeHandle = treeMapKey
            ? (treeMap) => {
                this[treeMapKey] = Object.assign({}, treeMap);
            }
            : null;
    }

    const handleNodesFromService = (nodes) => {
        (nodes || []).map((item) => {
            treeMap[item[idName]] = item;
        });
        if (!treeData || !treeData.length) {
            treeData = nodes;
        } else {
            //TODO 加入treeData
        }
        if (treeMapChangeHandle) {
            treeMapChangeHandle(treeMap);
        }
    };

    if (props && props.lazy) {
        let tempLoad = async (node, resolve) => {
            let params = {
                [queryIdName]: node.data[idName] || initParentCode,
                ...comParams,
                tenantId: this.tenantId,
            };

            if (paramsHandle) {
                params = paramsHandle(node);
            }
            // let userInfo=sessionStorage.getItem('userInfo');
            // await service("setUserSession", {
            //     params: {
            //         params:userInfo
            //     },
            //     noMessageTip: true
            // }).catch(() => {
            //     loading.close();
            // });

            let nodes = await service(serviceName, {
                [dataType]: params,
                // params: params,
                noMessageTip: true,
            });

            resolve(nodes);
        };

        if (props.lazyLoad) {
            tempLoad = props.lazyLoad;
        }

        props.lazyLoad = async (node, resolve) => {
            const treeResolve = (nodes) => {
                handleNodesFromService(nodes);
                if (nodes && nodes[0] && nodes[0].id === '0') {
                    nodes[0].disabled = true
                }
                resolve(nodes);
            };
            tempLoad(node, treeResolve);
        };
    }

    return (h, vm, item, value, handle) => {
        const changeHandle = (v) => {
            handle(v);
            // if (initInputKey) {
            //     vm.formData[initInputKey] = "";
            // }

        };

        return componentsType === "treeSelect" ? (
            <com-treeSelect
                ref="treeSelect"
                class="w-100"
                value={value}
                on-input={changeHandle}
                clearable={clearable}
                placeholder={placeholder}
                disabled={disabled}
                show-all-levels={showAllLevels}
                filter-method={filterMethod}
                options={options}
                collapseTags={collapseTags}
                props={{ props }}
                filterable={filterable}
                initInputText={vm.formData[initInputKey]}
            ></com-treeSelect>
        ) : (
            <el-cascader
                ref="comCascader"
                value={value}
                on-input={changeHandle}
                class="w-100"
                clearable={clearable}
                placeholder={placeholder}
                disabled={disabled}
                show-all-levels={showAllLevels}
                filter-method={filterMethod}
                options={options}
                collapseTags={collapseTags}
                props={{ props }}
                filterable={filterable}
            ></el-cascader>
        );
    };
}
// 工作组选择
export const groupCascaderFormRender = function (
    cascaderConfigs = {},
    serviceConfigs = {}
) {
    let treeMapKey = _.get(serviceConfigs, "treeMapKey");
    cascaderConfigs = {
        props: {
            lazy: true,
            checkStrictly: true,
            expandTrigger: "click",
            ...(cascaderConfigs.cascaderProps || {}),
        },
        ...cascaderConfigs,
    };
    serviceConfigs = {
        service: "selectGroupTree",
        paramsHandle: (node) => {
            return {
                id: _.get(node, "data.id"),
                tenantId: this.tenantId,
            };
        },
        treeMapChangeHandle: treeMapKey
            ? (treeMap) => {
                this[treeMapKey] = Object.assign({}, treeMap);
            }
            : noop,
        ...serviceConfigs,
    };

    return getCascaderFormRender.bind(this)(cascaderConfigs, serviceConfigs);
};
/* 组织机构 */
export const tissueTreeFormRender = function (
    cascaderConfigs = {},
    serviceConfigs = {}
) {
    let treeMapKey = _.get(serviceConfigs, "treeMapKey");
    cascaderConfigs = {
        props: {
            lazy: true,
            checkStrictly: true,
            expandTrigger: "click",
            ...(cascaderConfigs.cascaderProps || {}),
        },
        ...cascaderConfigs,
    };
    serviceConfigs = {
        service: "selectSamOrgaTree",
        paramsHandle: (node) => {
            return {
                id: _.get(node, "data.id"),
                tenantId: this.tenantId,
            };
        },
        treeMapChangeHandle: treeMapKey
            ? (treeMap) => {
                this[treeMapKey] = Object.assign({}, treeMap);
            }
            : noop,
        ...serviceConfigs,
    };

    return getCascaderFormRender.bind(this)(cascaderConfigs, serviceConfigs);
};

// 投诉主题
export const workTyeCascaderFormRender = function (
    cascaderConfigs = {},
    serviceConfigs = {}
) {
    let treeMapKey = _.get(serviceConfigs, "treeMapKey");
    let provCode = _.get(serviceConfigs, "provCode") || this.provCode;

    const filterMethod = async (key) => {
        let result = await service("findServReqTypeByCache", {
            data: {
                provCode,
                srvReqTypeName: key,
                isValid: "",
            },
        });
        let treeMap = {};

        result.forEach((item) => {
            treeMap[item.id] = item;
        });

        serviceConfigs.treeMapChangeHandle(treeMap);

        return flatNodesToNodes(result, treeMap);
    };

    cascaderConfigs = {
        showAllLevels: false,
        props: {
            lazy: true,
            checkStrictly: true,
            expandTrigger: "click",
            emitPath: false,
            ...(cascaderConfigs.cascaderProps || {}),
        },
        filterMethod,
        filterable: cascaderConfigs?.filterable || true,
        ...cascaderConfigs,
    };
    serviceConfigs = {
        // service: "findServReqType",
        service: "srvReqTypeRedisTree",
        paramsHandle: (node) => {
            return {
                suprSrvReqstTypeId: _.get(node, "data.id") || 0,
                provCode: provCode,
            };
        },
        treeMapChangeHandle: treeMapKey
            ? (treeMap) => {
                this[treeMapKey] = Object.assign({}, treeMap);
            }
            : noop,
        ...serviceConfigs,
    };
    return getCascaderFormRender.bind(this)(cascaderConfigs, serviceConfigs);
};

// 工作组
export const workGroupCascaderFormConfig = function (
    configs,
    { isActive = true, optionsGetHandle, params = {}, cache = true, dataIsFlat = false } = {}
) {
    let { key, label, treeMapKey } = configs || {};

    const nodesFilterHandle = (data) => {
        return treeFilter(
            data,
            (item) => {
                return Number(item.validFlag) === 1;
            },
            { childrenName: "children", keepByZeroChild: true }
        );
    };

    let initConfig = {
        type: "cascader",
        options: async () => {

            let { data, dataMap } = await this.$store.dispatch(
                "cfgTree/getCfgTree",
                {
                    service: "selectGroupTreeByStaffId",
                    params: params, // 接口入参
                    cache,
                    dataIsFlat,
                    ...(isActive
                        ? {
                            //   filterNodesKey: "queryServReqTypeTreeActive",
                            //   nodesFilterHandle: nodesFilterHandle,
                        }
                        : {}),
                }
            );
            //工作组组件禁选最大的父节点
            if (data && data[0] && data[0].id == '0' && configs.props.props.checkStrictly) {
                data[0].disabled = true
            }

            optionsGetHandle && optionsGetHandle(data, dataMap);

            this[treeMapKey ? treeMapKey : key + "treeMap"] = dataMap;

            return data;
        },
        props: {
            filterable: true,
            clearable: true,
            "popper-class": "workTypePop"
        },
    };
    return _.merge({}, initConfig, configs);
};

export const causeOfComplaintFormConfig = function (
    configs,
    { isActive = true } = {}
) {
    let { key, label, treeMapKey } = configs || {};

    const nodesFilterHandle = (data) => {
        return treeFilter(
            data,
            (item) => {
                return Number(item.validFlag) === 1;
            },
            { childrenName: "children", keepByZeroChild: true }
        );
    };

    let initConfig = {
        type: "cascader",
        options: async () => {
            let { data, dataMap } = await this.$store.dispatch(
                "cfgTree/getCfgTree",
                {
                    service: "queryComplaintvReqTypeTree",
                    data: {
                        provCode: this.provCode,
                        suprSrvReqstTypeId: "0",
                    },
                    dataIsFlat: false,
                    ...(isActive
                        ? {
                            filterNodesKey: "queryComplaintvReqTreeActive",
                            nodesFilterHandle: nodesFilterHandle,
                        }
                        : {}),
                }
            );
            this[treeMapKey ? treeMapKey : key + "treeMap"] = dataMap;
            data = data.filter((v) => v.validFlag);
            data = flatNodesToNodes(data)
            return data

        },
        props: {
            filterable: true,
            clearable: true,
            "popper-class": "workTypePop"
        },
    };
    return _.merge({}, initConfig, configs);
};
export const workTyeCascaderFormConfig = function (
    configs,
    { isActive = true } = {}
) {
    let { key, label, treeMapKey } = configs || {};

    const nodesFilterHandle = (data) => {
        return treeFilter(
            data,
            (item) => {
                return Number(item.validFlag) === 1;
            },
            { childrenName: "children", keepByZeroChild: true }
        );
    };

    let initConfig = {
        type: "cascader",
        options: async () => {
            let { data, dataMap } = await this.$store.dispatch(
                "cfgTree/getCfgTree",
                {
                    service: "queryServReqTypeTree",
                    data: {
                        provCode: this.provCode,
                        suprSrvReqstTypeId: "0",
                    },
                    dataIsFlat: false,
                    ...(isActive
                        ? {
                            filterNodesKey: "queryServReqTypeTreeActive",
                            nodesFilterHandle: nodesFilterHandle,
                        }
                        : {}),
                }
            );

            this[treeMapKey ? treeMapKey : key + "treeMap"] = dataMap;
            data = data.filter((v) => v.validFlag);
            data = flatNodesToNodes(data)
            return data;

        },
        props: {
            filterable: true,
            clearable: true,
            "popper-class": "workTypePop"
        },
    };
    return _.merge({}, initConfig, configs);
};

export const workTyeCascaderFormConfigBu = function (
    configs,
    { isActive = true } = {}
) {
    let { key, label, treeMapKey } = configs || {};

    const nodesFilterHandleBu = (data) => {
        return treeFilter(
            data,
            (item) => {
                return Number(item.validFlag) === 1;
            },
            { childrenName: "children", keepByZeroChild: true }
        );
    };

    let initConfigBu = {
        type: "cascader",
        options: async () => {
            let { data, dataMap } = await this.$store.dispatch(
                "cfgTree/getCfgTreeBu",
                {
                    service: "queryDeptServReqTypeTree",
                    data: {
                        provCode: this.provCode,
                        suprSrvReqstTypeId: "0",
                    },
                    ...(isActive
                        ? {
                            filterNodesKey: "queryServReqTypeTreeActive",
                            nodesFilterHandle: nodesFilterHandleBu,
                        }
                        : {}),
                }
            );

            this[treeMapKey ? treeMapKey : key + "treeMap"] = dataMap;
            return data;
        },
        props: {
            filterable: true,
            clearable: true,
            "popper-class": "workTypePop"
        },
    };
    return _.merge({}, initConfigBu, configs);
};


export const getTitleRender = ({ key, title }) => {
    return {
        key: key,
        type: "render",
        fullLine: true,
        noLabel: true,
        render: (h) => {
            return <div class="font-weight-bold">{title}</div>;
        },
    };
};

// 组织查询
export const selectSamOrgaTreeForCombotree = function (
    configs,
    { isActive = true, optionsGetHandle, params = {}, cache = true, dataIsFlat = false } = {}
) {
    let { key, label, treeMapKey } = configs || {};

    const nodesFilterHandle = (data) => {
        return treeFilter(
            data,
            (item) => {
                return Number(item.validFlag) === 1;
            },
            { childrenName: "children", keepByZeroChild: true }
        );
    };

    let initConfig = {
        type: "cascader",
        options: async () => {

            let { data, dataMap } = await this.$store.dispatch(
                "cfgTree/getCfgTree",
                {
                    service: "selectSamOrgaTreeForCombotree",
                    params: params, // 接口入参
                    cache,
                    dataIsFlat,
                    ...(isActive
                        ? {
                            //   filterNodesKey: "queryServReqTypeTreeActive",
                            //   nodesFilterHandle: nodesFilterHandle,
                        }
                        : {}),
                }
            );

            if (optionsGetHandle) {
                data = optionsGetHandle(data, dataMap)
            }
            // optionsGetHandle && optionsGetHandle(data, dataMap);

            this[treeMapKey ? treeMapKey : key + "treeMap"] = dataMap;


            return data;
        },
        props: {
            filterable: true,
            clearable: true,
            "popper-class": "workTypePop"
        },
    };
    return _.merge({}, initConfig, configs);
};

// 所属科室模糊搜索
export const queryDeptRender = function (set) {
    return createSelectFilterRenderHandle.bind(this)(set, {
        idName: "code",
        serviceHandle: async(params) => {
            return selectDeptList({
                ...params,
            })
        }, // srCfgCodes
        queryFiledName: "name",
        optionItemHandle: (item) => ({
            value: item.code,
            label: item.name,
        }),
        placeholder: "请输入数据源名称",
    });
};
// 角色模糊搜索
export const queryRoleRender = function (set) {
    return createSelectFilterRenderHandle.bind(this)(set, {
        idName: "code",
        serviceHandle: async(params) => {
            return selectRoleList({
                ...params,
            })
        }, // srCfgCodes
        queryFiledName: "name",
        optionItemHandle: (item) => ({
            value: item.code,
            label: item.name,
        }),
        placeholder: "请输入数据源名称",
    });
};
// 用户模糊搜索
export const queryUserRender = function (set) {
    return createSelectFilterRenderHandle.bind(this)(set, {
        idName: "id",
        serviceHandle: async(params) => {
            return selectUserList({
                ...params,
            })
        }, // srCfgCodes
        queryFiledName: "userName",
        optionItemHandle: (item) => ({
            value: item.id,
            label: item.userName,
        }),
        placeholder: "请输入数据源名称",
    });
};
// 患者模糊搜索
export const queryPatientRender = function (set) {
    return createSelectFilterRenderHandle.bind(this)(set, {
        idName: "id",
        serviceHandle: async(params) => {
            return selectPatientList({
                ...params,
            })
        }, // srCfgCodes
        queryFiledName: "name",
        optionItemHandle: (item) => ({
            ...item,
            value: item.id,
            label: item.name,
        }),
        placeholder: "请输入数据源名称",
    });
};

// 诊断
export const queryDiagnosisRender = function (set) {
    return createSelectFilterRenderHandle.bind(this)(set, {
        idName: "code",
        serviceHandle: async(params) => {
            return selectDiagnosisDictList({
                ...params,
            })
        }, // srCfgCodes
        queryFiledName: "name",
        optionItemHandle: (item) => ({
            ...item,
            value: item.code,
            label: item.name,
        }),
        placeholder: "请输入数据源名称",
    });
};
// 医嘱
export const queryOrderItemRender = function (set) {
    return createSelectFilterRenderHandle.bind(this)(set, {
        idName: "code",
        serviceHandle: async(params) => {
            return selectOrderItemDictList({
                ...params,
            })
        }, // srCfgCodes
        queryFiledName: "name",
        optionItemHandle: (item) => ({
            ...item,
            value: item.code,
            label: item.name,
        }),
        placeholder: "请输入数据源名称",
    });
};
export const queryTemplateItemRender = function (set) {
    return createSelectFilterRenderHandle.bind(this)({ nullQuerySign: true, ...set }, {
        idName: "tmpltId",
        serviceName: "queryCommonTplPageList",
        queryFiledName: "tplNm",
        optionItemHandle: (item) => ({
            value: item.tmpltId,
            label: item.tmpltNm,
        }),
        placeholder: "请输入模板名称",
    });
};

export const queryBankNoItemRender = function (set) {
    return createSelectFilterRenderHandle.bind(this)({ nullQuerySign: false, ...set }, {
        idName: "bankName",
        serviceName: "getBankInfoList",
        queryFiledName: "bankName",
        optionItemHandle: (item) => ({
            value: item.bankName,
            label: item.bankName,
            bankNo: item.bankNo,// 联行号
        }),
        placeholder: "请输入银行名称",
    });
};


export const querySectionItemRender = function (set) {
    return createSelectFilterRenderHandle.bind(this)({ nullQuerySign: false, ...set }, {
        idName: "sectionId",
        serviceName: "devOver",
        queryFiledName: "sectionName",
        optionItemHandle: (item) => ({
            value: item.sectionId,
            label: item.sectionName,
        }),
        placeholder: "请输入路段名称",
    });
}
export const queryStationItemRender = function (set) {
    return createSelectFilterRenderHandle.bind(this)({ nullQuerySign: false, ...set }, {
        idName: "stationId",
        serviceName: "handleInternal",
        queryFiledName: "stationName",
        params: { ...set.params || {} },
        optionItemHandle: (item) => ({
            value: item.stationId,
            label: item.stationName,
        }),
        placeholder: "请输入收费站名称",
    });
}
// 调账单号选择
export const queryAdjustNoItemRender = function (set) {
    return createSelectFilterRenderHandle.bind(this)({ showSelectAll: true, nullQuerySign: true, ...set }, {
        idName: "adjustNo",
        serviceName: "adjustNoQueryList",
        queryFiledName: "adjustNo",
        optionItemHandle: (item) => ({
            value: item.adjustNo,
            label: item.adjustNo,
        }),
        placeholder: "请输入调账单号",
    });
}
// 业主模糊搜索选择
export const queryOwnerItemRender = function (set) {
    return createSelectFilterRenderHandle.bind(this)({ nullQuerySign: true, ...set }, {
        idName: "ownCode",
        serviceName: "ownerQueryList",
        queryFiledName: "ownName",
        optionItemHandle: (item) => ({
            value: item.ownCode,
            label: item.ownName,
        }),
        placeholder: "请输入业主名称",
    });
}
// 路段模糊搜索选择
export const queryRoadItemRender = function (set) {
    return createSelectFilterRenderHandle.bind(this)({ nullQuerySign: true, ...set }, {
        idName: "GROUPTYPEID",
        serviceName: "examineDataBlurQuery",
        queryFiledName: "outroadNm",
        optionItemHandle: (item) => ({
            value: item.GROUPTYPEID,
            label: item.GROUPTYPENAME,
        }),
        placeholder: "请输入路段名称",
    });
}

// 类型模糊搜索选择
export const queryTypeItemRender = function (set) {
    return createSelectFilterRenderHandle.bind(this)({ nullQuerySign: true, ...set }, {
        idName: "id",
        serviceName: "selectLiketypes",
        queryFiledName: "types",
        optionItemHandle: (item) => ({
            value: item.types,
            label: item.types,
        }),
        placeholder: "请输入类型名称",
    });
}

// 入口站选择
export const queryEnStationItemRender = function (set) {
    return createSelectFilterRenderHandle.bind(this)({ nullQuerySign: false, ...set }, {
        idName: "stationId",
        serviceName: "queryStationinfoByName",
        queryFiledName: "stationName",
        optionItemHandle: (item) => ({
            value: item.stationId,
            label: item.stationName,
        }),
        placeholder: "请输入口站",
    });
}
// 出口站选择 已废弃
export const queryExStationItemRender = function (set) {
    return createSelectFilterRenderHandle.bind(this)({ nullQuerySign: false, ...set }, {
        idName: "exStationId",
        serviceName: "devOver",
        queryFiledName: "exStationId",
        optionItemHandle: (item) => ({
            value: item.exStationId,
            label: item.exTollStationName,
        }),
        placeholder: "请输入出口站",
    });
}
// 短信模板模糊搜索
export const querySmsItemRender = function (set) {
    return createSelectFilterRenderHandle.bind(this)({ nullQuerySign: true, ...set }, {
        idName: "id",
        serviceName: "getRecordList",
        queryFiledName: "title",
        optionItemHandle: (item) => ({
            value: item.id,
            label: item.title,
            content: item.content
        }),
        placeholder: "请输入模板名称",
    });
};
// 技能模糊搜索
export const querySkillRender = function (set) {
    return createSelectFilterRenderHandle.bind(this)({ nullQuerySign: true, ...set }, {
        idName: "skillId",
        serviceName: "cmg_qrySkillConfigs",
        queryFiledName: "skillName",
        optionItemHandle: (item) => {
            return {
                value: item.skillId,
                label: item.skillName,
            }
        },
        placeholder: "请搜索技能名称",
    });
};
function createSelectFilterRenderHandle(
    {
        clearable = false,
        initList,
        onDataMapHandle,
        getSetOptionHandle,
        getRemoteMethodHandle,
        className,
        multiple = false,
        collapseTags = true,
        nullQuerySign = false,
        disabled = false,
        params,
        queryParamHandle,
        showSelectAll = false,
        selectSet,
        changeOptionsOut,
        formChangeHandle,
        slotRender = {},
    } = {},
    {
        idName = "value",
        serviceName,
        serviceHandle,
        queryFiledName,
        optionItemHandle,
        afterQueryListHandle,
        placeholder,
    } = {}
) {
    let options = initList || [];
    let loading = false;
    let dataMap = {};
    let queryed = false;

    if (initList && initList.length) {
        initList.map((item) => {
            dataMap[item[idName]] = item;
        });

        if (onDataMapHandle) {
            onDataMapHandle(dataMap);
        }
    }

    if (getSetOptionHandle) {
        getSetOptionHandle((data) => {
            data.map((item) => {
                dataMap[item[idName]] = item;
            });

            if (onDataMapHandle) {
                onDataMapHandle(dataMap);
            }

            options = data;
        });
    }

    return (h, vm, item, data, formChange) => {
        const changeHandle = (...rest) => {
            formChange(...rest);
            if (formChangeHandle) {
                formChangeHandle(vm, ...rest);
            }
        }
        const selectAll = () => {
            if (!Array.isArray(options)) {
                return;
            }
            let allKey = options.map((v) => v[idName]);
            changeHandle(allKey);
        };

        const deSelectAll = () => {
            changeHandle([]);
        };

        const changeOptions = (ops) => {
            options = ops;
            vm.$forceUpdate();
        }

        const clearHandle = () => {
            remoteMethod();
        }

        if (changeOptionsOut) {
            changeOptionsOut(changeOptions);
        }

        let remoteMethod = async (query) => {
            if (query !== "" || nullQuerySign) {
                queryed = true;

                loading = true;

                loading = false;

                let queryParam = {
                    [queryFiledName]: query,
                    page: { pageNo: 1, pageSize: 100 },
                    pageNum: 1,
                    pageSize: 100,
                    ...(params || {}),
                };
                if (queryParamHandle) {
                    queryParam = queryParamHandle(queryParam);
                }

                // let result = await ocj.post({
                //     url: api.get(service),
                //     data: queryParam
                // });

                
                // let result = await service(vm.formData[slotRender.key] == '1' ? slotRender.serviceName : serviceName, {
                //     data: queryParam,
                //     noMessageTip: true,
                // });

                let result = await serviceHandle(queryParam)
                let list = null;
                if (!result) {
                    return;
                } else if (Array.isArray(result)) {
                    list = result;
                } else if (Array.isArray(result.result)) {
                    list = result.result;
                } else if (Array.isArray(result.data)) {
                    list = result.data;
                } else if (Array.isArray(result.list)) {
                    list = result.list;
                } else if (Array.isArray(result.datas)) {
                    list = result.datas;
                }  else if (Array.isArray(result.rows)) {
                    list = result.rows;
                } else {
                    return;
                }

                if (afterQueryListHandle) {
                    list = await afterQueryListHandle(list);

                }
                list.forEach((item) => {
                    dataMap[item[idName]] = item;
                });

                options = list;

                if (onDataMapHandle) {
                    onDataMapHandle(dataMap);
                }
                console.log("🚀 ~ file: formRender.js ~ line 1154 ~ remoteMethod ~ list", options)

            } else {
                options = [];
            }

            vm.$forceUpdate();
        };

        // remoteMethod = _.throttle(remoteMethod,2000)
        if (nullQuerySign && !queryed) {
            remoteMethod();
        }
        if (getRemoteMethodHandle) {
            getRemoteMethodHandle(remoteMethod);
        }

        let component
        if (slotRender.key) {
            let handleSelect = value => {
                vm.formData[slotRender.key] = value;
                vm.setFormData({ [slotRender.key]: value })
                this[slotRender.key](vm)
            }
            let optionList = [
                { value: '0', label: '收费站' },
                { value: '1', label: '收费单元' },
            ]
            if (vm.formData[slotRender.key] == undefined) {
                //默认选择收费站
                vm.formData[slotRender.key] = '0'
            }
            component = (<el-select style="width:38%;" value={vm.formData[slotRender.key]} on-change={handleSelect} >
                {
                    (optionList || []).map(item => {
                        return <el-option key={item.value} label={item.label} value={item.value}></el-option>
                    })
                }
            </el-select>)
        }

        return (<div class="w-100 el-select">
            {component}
            <el-select
                value={data}
                on-input={changeHandle}
                on-blur={selectSet?.onblur || (() => { })}
                on-focus={selectSet?.onfocus || (() => { })}
                on-clear={clearHandle}
                filterable
                remote
                reserve-keyword
                placeholder={vm.formData[slotRender.key] == '2' ? '请输入收费单元名称' : placeholder}
                remote-method={remoteMethod}
                clearable={clearable}
                loading={loading}
                class={className}
                multiple={multiple}
                collapse-tags={collapseTags}
                disabled={disabled}
                {...(selectSet ? selectSet : {})}
            >
                {showSelectAll ? (
                    <div
                        class="px-20 py-8"
                        style={`
                                position: sticky;
                                top: 0;
                                background-color: rgb(255, 255, 255);
                                z-index: 1;
                                margin-right: 0;
                                margin-top: -6px;
                            `}
                    >
                        <span class="blue-text-button" on-click={selectAll}>
                            全选
                        </span>
                        &nbsp;&nbsp;&nbsp;&nbsp;
                        <span class="blue-text-button" on-click={deSelectAll}>
                            全不选
                        </span>
                    </div>
                ) : null}
                {options
                    .map((item) => {
                        if (item.value && item.label) {
                            return item;
                        }

                        if (optionItemHandle) {
                            return optionItemHandle(item);
                        }

                        return {
                            value: item[idName],
                            label: item.label,
                        };
                    })
                    .map((item, index) => {
                        return (
                            <el-option
                                key={index}
                                label={item.label}
                                value={item.value}
                            />
                        );
                    })}
            </el-select>
        </div>
        );
    };
}
/**
 *
 * @param {Object} IVRSelectConfig IVR选择组件的配置
 */

export const getIVRFormItemRender = ({
    disabled,
    selectConfig,
} = {}) => {
    return getPaginationSelectRenderGenerater(
        {
            asyncHandle: getIVRAsync(selectConfig),
            configName: "IVRSelectConfig",
            showHandle: (data) => {
                if (Array.isArray(data)) {
                    return data.length
                        ? data.map((v) => v.name).join(",")
                        : "";
                } else {

                    return data ? `${data.name}` : "";
                }

            },
        },
        { disabled, selectConfig }
    );

};
/**
 *
 * @param {Object} SelectConfig 质检员选择组件的配置
 */

export const checkStaffFormItemRender = ({
    disabled,
    selectConfig,
} = {}) => {
    return getPaginationSelectRenderGenerater(
        {
            asyncHandle: checkStaffAsync(selectConfig),
            configName: "checkStaffSelectConfig",
            showHandle: (data) => {
                if (Array.isArray(data)) {
                    return data.length
                        ? data.map((v) => v.staffName).join(",")
                        : "";
                } else {
                    return data ? `${data.staffName}` : "";
                }

            },
        },
        { disabled, selectConfig }
    );

};
/**
 *
 * @param {Object} SelectConfig 考评计划选择组件的配置
 */

export const examinationPlanFormItemRender = ({
    disabled,
    selectConfig,
} = {}) => {
    return getPaginationSelectRenderGenerater(
        {
            asyncHandle: examinationPlanAsync(selectConfig),
            configName: "examinationPlanSelectConfig",
            showHandle: (data) => {
                if (Array.isArray(data)) {
                    return data.length
                        ? data.map((v) => v.planName).join(",")
                        : "";
                } else {
                    return data ? `${data.planName}` : "";
                }

            },
        },
        { disabled, selectConfig }
    );

};

/**
 *
 * @param {Object} SelectConfig 考评模板选择组件的配置
 */

export const examinationTemplateFormItemRender = ({
    disabled,
    selectConfig,
} = {}) => {
    return getPaginationSelectRenderGenerater(
        {
            asyncHandle: examinationTemplateAsync(selectConfig),
            configName: "examinationTemplateSelectConfig",
            showHandle: (data) => {
                if (Array.isArray(data)) {
                    return data.length
                        ? data.map((v) => v.templateName).join(",")
                        : "";
                } else {
                    return data ? `${data.templateName}` : "";
                }

            },
        },
        { disabled, selectConfig }
    );

};

